<template>
  <div class="visit-process">
    <!-- 进度概览卡片 -->
    <div class="progress-overview">
      <el-card :body-style="{ padding: 0 }" class="progress-card">
        <div>
          <div class="progress-header">
            <h3>走访进度概览</h3>
            <div class="progress-percentage">{{ overallProgress }}%</div>
          </div>
          <el-progress :percentage="overallProgress" :status="progressStatus" :text-inside="true" :stroke-width="20" />
          <div class="progress-details">
            <span>走访计划: {{ planInfo.planName }}</span>
            <span>已完成 {{ completedTargets }}/{{ totalTargets }} 项目标</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 计划基本信息 -->
    <el-card class="form-section">
      <template #header>
        <div class="section-title">计划基本信息</div>
      </template>
      <div class="info-grid">
        <div class="info-item">
          <label>计划编号</label>
          <span>{{ planInfo.planCode }}</span>
        </div>
        <div class="info-item">
          <label>计划名称</label>
          <span>{{ planInfo.planName }}</span>
        </div>
        <div class="info-item">
          <label>计划开始时间</label>
          <span>{{ planInfo.startTime }}</span>
        </div>
        <div class="info-item">
          <label>计划结束时间</label>
          <span>{{ planInfo.endTime }}</span>
        </div>
        <div class="info-item">
          <label>负责人</label>
          <span>{{ planInfo.manager }}</span>
        </div>
        <div class="info-item">
          <label>联系电话</label>
          <span>{{ planInfo.managerPhone }}</span>
        </div>
        <div class="info-item">
          <label>计划状态</label>
          <span :class="['status-tag', planInfo.statusClass]">{{ planInfo.statusText }}</span>
        </div>
        <div class="info-item">
          <label>备注</label>
          <span>{{ planInfo.remark }}</span>
        </div>
      </div>
    </el-card>

    <!-- 客户信息 -->
    <el-card class="form-section">
      <template #header>
        <div class="section-title">客户信息</div>
      </template>
      <div class="info-grid">
        <div class="info-item">
          <label>客户名称</label>
          <span class="clickable-customer" @click="viewCustomerDetail">
            {{ customerInfo.name }}
            <el-icon><arrow-right /></el-icon>
          </span>
        </div>
        <div class="info-item">
          <label>客户类型</label>
          <span>{{ customerInfo.type }}</span>
        </div>
        <div class="info-item">
          <label>联系人</label>
          <span>{{ customerInfo.contactPerson }}</span>
        </div>
        <div class="info-item">
          <label>联系电话</label>
          <span>{{ customerInfo.contactPhone }}</span>
        </div>
        <div class="info-item">
          <label>客户地址</label>
          <span>{{ customerInfo.address }}</span>
        </div>
        <div class="info-item">
          <label>上次走访</label>
          <span>{{ customerInfo.lastVisit }}</span>
        </div>
      </div>
    </el-card>

    <!-- 走访记要 -->
    <el-card class="form-section">
      <template #header>
        <div class="section-title">走访记要</div>
      </template>
      <div class="visit-notes">
        <div class="note-item">
          <div class="note-header">
            <div class="note-meta">
              <div class="note-author">{{ visitNotes.author }}</div>
              <div class="note-time">{{ visitNotes.timestamp }}</div>
            </div>
            <div class="note-tags">
              <el-tag v-for="tag in visitNotes.tags" :key="tag" size="small" type="primary">
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <div class="note-content">
            <div class="note-section">
              <h4>客户反馈</h4>
              <p>{{ visitNotes.customerFeedback }}</p>
            </div>
            <div class="note-section">
              <h4>业务机会</h4>
              <ul>
                <li v-for="(opportunity, index) in visitNotes.businessOpportunities" :key="index">
                  {{ opportunity }}
                </li>
              </ul>
            </div>
            <div class="note-section">
              <h4>跟进待办</h4>
              <div v-for="todo in visitNotes.followUpTodos" :key="todo.content" class="todo-item">
                <el-checkbox v-model="todo.completed" :disabled="true" />
                <span>{{ todo.content }}</span>
                <span class="todo-deadline">{{ todo.deadline }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 走访目标详情 -->
    <el-card class="form-section">
      <template #header>
        <div class="section-title">走访目标详情</div>
      </template>
      <div v-for="(target, index) in visitTargets" :key="target.id" class="target-item">
        <div class="target-header">
          <div class="target-title">
            目标 {{ index + 1 }}：{{ target.targetName }}
          </div>
          <div class="target-status" :class="target.statusClass">
            {{ target.statusText }}
            <span v-if="target.completedTime"> ({{ target.completedTime }})</span>
          </div>
        </div>
        <el-collapse-transition>
          <div v-if="expandedTargets[index]">
            <div class="target-content">
              <div class="target-field">
                <label>目标描述</label>
                <span>{{ target.description }}</span>
              </div>
              <div class="target-field">
                <label>准备事项</label>
                <div class="target-tags">
                  <span v-for="prep in target.selectedPreparations" :key="prep" class="tag-item selected">
                    {{ getPreparationLabel(prep) }}
                  </span>
                  <span v-for="prep in target.customPreparations" :key="prep" class="tag-item custom-tag">
                    {{ prep }}
                  </span>
                </div>
              </div>
              <div class="target-field">
                <label>走访记录</label>
                <span>{{ target.visitRecord }}</span>
              </div>

              <!-- 产品推荐 -->
              <div v-if="target.recommendedProducts && target.recommendedProducts.length > 0">
                <label>推荐产品</label>
                <div class="product-recommendation">
                  <div class="product-list">
                    <div v-for="product in target.recommendedProducts" :key="product.id" class="product-item">
                      <div class="product-info">
                        <div class="product-name">{{ product.name }}</div>
                        <div class="product-desc">{{ product.description }}</div>
                        <div class="product-price">{{ product.price }}</div>
                      </div>
                      <div class="product-intention">
                        <span>客户意向：</span>
                        <span class="selected-intention">{{ product.intention }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 关键人信息 -->
              <div v-if="target.keyPersons && target.keyPersons.length > 0">
                <label>关键人信息</label>
                <el-table :data="target.keyPersons" size="small" border>
                  <el-table-column prop="name" label="姓名" width="100" />
                  <el-table-column prop="department" label="部门" width="120" />
                  <el-table-column prop="position" label="职位" width="150" />
                  <el-table-column prop="gender" label="性别" width="80" />
                  <el-table-column prop="contactNumber" label="联系电话" width="150" />
                  <el-table-column prop="role" label="角色" width="120" />
                </el-table>
              </div>
            </div>
          </div>
        </el-collapse-transition>
        <div style="margin-top: 15px; text-align: right;">
          <el-button type="text" size="small" @click="toggleTargetExpand(index)">
            {{ expandedTargets[index] ? '收起' : '展开' }}
            <el-icon><caret-top v-if="expandedTargets[index]" /><caret-bottom v-else /></el-icon>
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="$emit('close')">关闭</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ArrowRight, CaretTop, CaretBottom } from '@element-plus/icons-vue';
import type { Ref } from 'vue';

// 定义类型接口
interface PresetPreparation {
  value: string;
  label: string;
}

interface PlanInfo {
  planCode: string;
  planName: string;
  startTime: string;
  endTime: string;
  manager: string;
  managerPhone: string;
  status: string;
  statusText: string;
  statusClass: string;
  remark: string;
}

interface CustomerInfo {
  id: string;
  name: string;
  type: string;
  contactPerson: string;
  contactPhone: string;
  address: string;
  lastVisit: string;
}

interface TodoItem {
  content: string;
  deadline: string;
  completed: boolean;
}

interface VisitNote {
  author: string;
  timestamp: string;
  tags: string[];
  customerFeedback: string;
  businessOpportunities: string[];
  followUpTodos: TodoItem[];
}

interface RecommendedProduct {
  id: string;
  name: string;
  description: string;
  price: string;
  intention: string;
}

interface KeyPerson {
  id: string;
  name: string;
  department: string;
  contactNumber: string;
  gender: string;
  position: string;
  role: string;
}

interface VisitTarget {
  id: string;
  targetName: string;
  selectedPreparations: string[];
  customPreparations: string[];
  description: string;
  completed: boolean;
  completedTime: string;
  visitRecord: string;
  statusText: string;
  statusClass: string;
  recommendedProducts?: RecommendedProduct[];
  keyPersons?: KeyPerson[];
}

// 预设准备事项选项
const presetPreparations: PresetPreparation[] = [
  { value: 'BROCHURE', label: '产品手册' },
  { value: 'SAMPLE', label: '样品' },
  { value: 'CONTRACT', label: '合同' },
  { value: 'REPORT', label: '报告' },
  { value: 'GIFT', label: '礼品' },
  { value: 'OTHER', label: '其他' }
];

// 走访目标展开状态 - 两个目标默认都展开
const expandedTargets: Ref<boolean[]> = ref([true, true]);

// 计划基本信息
const planInfo: PlanInfo = reactive({
  planCode: 'VISIT-202307-001',
  planName: '季度客户回访计划',
  startTime: '2023-07-10 09:00:00',
  endTime: '2023-07-10 11:30:00',
  manager: '张三',
  managerPhone: '13800138000',
  status: '1',
  statusText: '进行中',
  statusClass: 'status-in-progress',
  remark: '季度例行客户回访，了解产品使用情况和客户需求'
});

// 客户信息
const customerInfo: CustomerInfo = reactive({
  id: '1',
  name: 'ABC贸易有限公司',
  type: '经销商',
  contactPerson: '李四',
  contactPhone: '13900139000',
  address: '北京市朝阳区建国路88号',
  lastVisit: '2023-04-15 14:30:00'
});

// 走访记要信息
const visitNotes: VisitNote = reactive({
  author: '张三 (客户经理)',
  timestamp: '2023-07-10 11:00:00',
  tags: ['重点客户', '业务增长', '产品升级'],
  customerFeedback: '客户对当前使用的企业宽带服务非常满意，特别提到了24小时技术支持的响应速度。对企业云通信平台表现出浓厚兴趣，认为可以提升内部沟通效率。同时，客户也提到了竞争对手最近推出的类似服务，价格略低但功能相对简单。',
  businessOpportunities: [
    '客户计划在本季度扩大业务范围，预计新增20个办公点，需要批量部署网络和通信服务',
    '客户正在考虑升级现有系统，对集成化解决方案有需求',
    '客户有兴趣了解物联网解决方案，用于监控仓库和物流',
    '客户愿意作为我们新产品的试点用户，前提是能提供一定的优惠政策'
  ],
  followUpTodos: [
    {
      content: '提供企业云通信平台的详细方案和报价',
      deadline: '2023-07-15',
      completed: true
    },
    {
      content: '制定多办公点网络部署的整体解决方案',
      deadline: '2023-07-20',
      completed: false
    },
    {
      content: '安排技术团队与客户IT部门进行深入交流',
      deadline: '2023-07-25',
      completed: false
    },
    {
      content: '准备物联网解决方案演示',
      deadline: '2023-07-30',
      completed: false
    }
  ]
});

// 走访目标列表
const visitTargets: VisitTarget[] = reactive([
  {
    id: '1',
    targetName: '产品营销',
    selectedPreparations: ['BROCHURE', 'SAMPLE'],
    customPreparations: ['最新价格表'],
    description: '向客户详细介绍我司三款核心企业级电信产品：企业宽带增值套餐（高速稳定含24小时技术支持）、企业云通信平台（集成语音/视频会议/即时通讯）和物联网智能连接服务（支持远程监控与管理），了解客户对这些产品的需求和意向，同时收集现有产品使用情况和反馈建议。',
    completed: true,
    completedTime: '2023-07-10 09:45:00',
    visitRecord: '客户对新产品表示浓厚兴趣，特别是针对中小企业的解决方案。现有产品使用情况良好，没有重大问题。',
    statusText: '已完成',
    statusClass: 'status-completed',
    recommendedProducts: [
      {
        id: 'product1',
        name: '企业宽带增值套餐',
        description: '高速稳定的企业宽带服务，含24小时技术支持和数据备份功能',
        price: '¥1,999/月',
        intention: '再考虑'
      },
      {
        id: 'product2',
        name: '企业云通信平台',
        description: '集成语音、视频会议、即时通讯的统一通信解决方案',
        price: '¥3,580/月',
        intention: '接受'
      },
      {
        id: 'product3',
        name: '物联网智能连接服务',
        description: '为企业设备提供稳定可靠的物联网连接，支持远程监控和管理',
        price: '¥2,380/月',
        intention: '不接受'
      }
    ]
  },
  {
    id: '2',
    targetName: '关键人信息收集',
    selectedPreparations: ['REPORT'],
    customPreparations: ['竞争对手分析报告'],
    description: '收集客户关键联系人信息，了解组织结构',
    completed: true,
    completedTime: '2023-07-10 10:30:00',
    visitRecord: '已收集客户3位关键联系人信息，了解了客户的组织结构和决策流程。',
    statusText: '已完成',
    statusClass: 'status-completed',
    keyPersons: [
      {
        id: '1',
        name: '李四',
        department: '采购部',
        contactNumber: '13900139000',
        gender: '男',
        position: '采购经理',
        role: '决策者'
      },
      {
        id: '2',
        name: '王五',
        department: '技术部',
        contactNumber: '13700137000',
        gender: '男',
        position: '技术总监',
        role: '技术评估者'
      },
      {
        id: '3',
        name: '赵六',
        department: '财务部',
        contactNumber: '13600136000',
        gender: '女',
        position: '财务主管',
        role: '预算审批'
      }
    ]
  }
]);

// 计算总目标数
const totalTargets = computed(() => {
  return visitTargets.length;
});

// 计算已完成目标数
const completedTargets = computed(() => {
  return visitTargets.filter(target => target.completed).length;
});

// 计算总体进度
const overallProgress = computed(() => {
  if (totalTargets.value === 0) return 0;
  return Math.round((completedTargets.value / totalTargets.value) * 100);
});

// 进度状态
const progressStatus = computed(() => {
  if (overallProgress.value === 100) return 'success';
  if (overallProgress.value > 0) return 'exception';
  return 'normal';
});

// 获取准备事项标签文本
const getPreparationLabel = (value: string): string => {
  const prep = presetPreparations.find(item => item.value === value);
  return prep ? prep.label : value;
};

// 切换目标卡片展开/折叠状态
const toggleTargetExpand = (targetIndex: number): void => {
  expandedTargets.value[targetIndex] = !expandedTargets.value[targetIndex];
};

// 查看客户详情
const viewCustomerDetail = (): void => {
  // 这里会通过emit事件通知父组件
};

// 定义emits
// const emit = defineEmits<{
//   'close': [];
//   'view-customer-detail': [customerId: string];
// }>();
</script>

<style scoped>
.visit-process {
  font-size: 14px;
}

/* 进度概览卡片 */
.progress-overview {
  margin-bottom: 20px;
}

.progress-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.progress-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: normal;
}

.progress-percentage {
  font-size: 24px;
  font-weight: bold;
}

.progress-details {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 12px;
  opacity: 0.8;
}

/* 表单区块 */
.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

/* 信息网格 */
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-item label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 4px;
}

.info-item span {
  color: #303133;
}

/* 状态标签 */
.status-tag {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
}

.status-pending {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.status-in-progress {
  background-color: #ecf5ff;
  color: #409eff;
}

.status-completed {
  background-color: #f0f9eb;
  color: #67c23a;
}

.status-canceled {
  background-color: #fef0f0;
  color: #f56c6c;
}

/* 目标项 */
.target-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.target-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.target-title {
  font-weight: bold;
}

.target-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
}

/* 目标内容 */
.target-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.target-field {
  display: flex;
  flex-direction: column;
}

.target-field label {
  color: #909399;
  font-size: 12px;
  margin-bottom: 4px;
}

/* 标签容器 */
.target-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

/* 标签样式 */
.tag-item {
  display: inline-flex;
  align-items: center;
  padding: 4px 12px;
  background-color: #f0f2f5;
  border-radius: 16px;
  color: #606266;
  font-size: 12px;
}

.tag-item.selected {
  background-color: #409eff;
  color: #ffffff;
}

/* 自定义标签样式 */
.custom-tag {
  background-color: #52c41a;
  color: #ffffff;
}

/* 产品推荐区域样式 */
.product-recommendation {
  margin-top: 16px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.product-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 8px;
}

.product-item {
  padding: 12px;
  background-color: white;
  border: 1px solid #e6e6e6;
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.product-info {
  flex: 1;
}

.product-name {
  font-weight: bold;
  font-size: 16px;
  color: #333;
  margin-bottom: 4px;
}

.product-desc {
  color: #666;
  font-size: 14px;
  margin-bottom: 4px;
}

.product-price {
  color: #e64340;
  font-weight: bold;
  font-size: 14px;
}

.product-intention {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 8px;
}

.selected-intention {
  color: #1989fa;
  font-size: 14px;
  font-weight: 500;
}

/* 操作按钮 */
.form-actions {
  margin-top: 20px;
  text-align: right;
}

/* 可点击的客户名称样式 */
.clickable-customer {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: color 0.3s;
}

.clickable-customer:hover {
  color: #409eff;
}

/* 走访记要样式 */
.visit-notes {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
}

.note-item {
  background-color: white;
  border-radius: 6px;
  padding: 15px;
  border-left: 4px solid #409eff;
}

.note-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

.note-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.note-author {
  font-weight: bold;
  color: #303133;
}

.note-time {
  color: #909399;
  font-size: 12px;
}

.note-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.note-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.note-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.note-section h4 {
  margin: 0;
  font-size: 14px;
  color: #303133;
  font-weight: bold;
}

.note-section p {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.note-section ul {
  margin: 0;
  padding-left: 20px;
}

.note-section li {
  line-height: 1.8;
  color: #606266;
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
}

.todo-deadline {
  margin-left: auto;
  color: #909399;
  font-size: 12px;
}
</style>